// src/hooks/useDarkMode.ts
import { ref, watch } from 'vue';

export function useDarkMode() {
  // 从本地存储获取初始主题
  const isDark = ref(localStorage.getItem('theme') === 'dark');

  // 切换主题
  const toggleDark = () => {
    isDark.value = !isDark.value;
    localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
  };

  // 监听主题变化并应用
  watch(isDark, (newValue) => {
    document.documentElement.classList.toggle('dark', newValue);
  }, { immediate: true });

  // 监听系统主题变化
  const systemDark = window.matchMedia('(prefers-color-scheme: dark)');
  systemDark.addEventListener('change', (e) => {
    if (localStorage.getItem('theme') === null) {
      isDark.value = e.matches;
    }
  });

  return {
    isDark,
    toggleDark
  };
}
